package middleware

import (
	"encoding/json"
	"fmt"
	"net/http"
	"wx_order_server/internal/utils"

	"github.com/imroc/req/v3"
	"github.com/tidwall/gjson"
)

// 路径白名单
var whiteList = []string{
	"/autoGroup/v1/login",
	"/autoGroup/v1/register",
	"/autoGroup/v1/user",
}

type AuthInfo struct {
	Iat int64  `json:"iat"`
	Aud string `json:"aud"`
	Exp int64  `json:"exp"`
}

func AuthTokenIsPass(token string, host string) string {
	// token 去掉空格
	redisKey := utils.GetRedisKey(token)

	authInfo, rGetErr := utils.RGet[AuthInfo](redisKey)

	if authInfo.Iat != 0 && rGetErr == nil {
		return fmt.Sprintf(`{"iat":%d,"aud":"%s","exp":%d}`, authInfo.Iat, authInfo.Aud, authInfo.Exp)
	}

	response, err := req.C().SetCommonHeaders(
		map[string]string{
			"Authorization": token,
		},
	).R().Post(host + "/group/v1/group/checkToken")
	if err != nil {
		return ""
	}

	resStr, _ := response.ToString()
	data := gjson.Get(resStr, "data").String()

	if data == "" {
		return ""
	}
	authInfo = AuthInfo{}

	err = json.Unmarshal([]byte(data), &authInfo)
	if err != nil {
		return ""
	}

	utils.RSaveLimit(redisKey, authInfo, 3600*12)

	return data
}

func AuthToken(next http.HandlerFunc, host string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 判断是否在白名单中
		for _, path := range whiteList {
			// 包含路径
			if path == r.URL.Path {
				next(w, r)
				return
			}
		}

		token := r.Header.Get("Authorization")
		if token == "" {
			http.Error(w, "token is required", http.StatusUnauthorized)
			return
		} else {
			if AuthTokenIsPass(token, host) == "" {
				http.Error(w, "token is invalid", http.StatusUnauthorized)
				return
			}
		}

		next(w, r)
	}
}
